package org.cskj.demo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
//当配置文件中cors.enable=true，才会进行注入
@ConditionalOnProperty(name ="cors.enable",havingValue = "true",matchIfMissing = true)
//自动配置属性
@EnableConfigurationProperties({CrossProperty.class})
public class CrossConfig implements Filter{
    //DI 属性类
    @Autowired
    private CrossProperty crossProperty;

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse res= (HttpServletResponse) servletResponse;
        //进行跨域请求设置
        //允许携带cookie
        res.addHeader("Access-Control-Allow-Credentials", crossProperty.getCredentials());
        //设置访问控制允许源
        res.addHeader("Access-Control-Allow-Origin", crossProperty.getOrigin());
        //设置cookie最大存活时常
        res.addHeader("Access-Control-Allow-Max-Age", crossProperty.getMaxAge());
        //设置允许方法,如果设置*代表全部
        res.addHeader("Access-Control-Allow-Methods", crossProperty.getMethods());
        //res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
        //因为请求时携带了两个信息在请求头中【token，usid】，因此需要在响应头中设置上这两个内容
        //res.addHeader("Access-Control-Allow-Headers","token,usid,content-type");
        //处理Options请求【预检请求，常见ajax，ajax发出正式请求【get/post】，会先发出预检请求】
        if (((HttpServletRequest) servletRequest).getMethod().equals("OPTIONS")) {
            servletResponse.getWriter().println("ok");
            return;
        }
        //放过请求
        filterChain.doFilter(servletRequest,servletResponse);
    }
}